package com.travel.shop.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.travel.entity.dto.ListResultVO;
import com.travel.entity.dto.ResultVO;
import com.travel.entity.goodsEn.TravelGoods;
import com.travel.entity.shop.TravelShop;
import com.travel.goodsApi.IGoodsAPI;
import com.travel.shop.mapper.TravelShopMapper;
import com.travel.shop.service.ITravelShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author muzi
 * @since 2021-04-15
 */
@Service
public class TravelShopServiceImpl extends ServiceImpl<TravelShopMapper, TravelShop> implements ITravelShopService {

    @Autowired
    private TravelShopMapper travelShopMapper;

    @Autowired(required = false)
    private IGoodsAPI iGoodsAPI;

    @Autowired
    private StringRedisTemplate template;

    @Override
    public ResultVO<TravelShop> findShopById(String shopId) {
        if (shopId == null) return new ResultVO<>(false, "查询失败");

        //查询商家信息
        TravelShop shop = travelShopMapper.selectById(shopId);
        //判断商家是否存在
        if (shop == null) {
            return new ResultVO<>(false, "查询失败");
        }
        List goodsList = null;
        //通过远程调用商品微服务,查询该商家的所有产品
        ResultVO result = iGoodsAPI.findListByShopId(shopId);
        if (result.isFlag()) {
            Set<ZSetOperations.TypedTuple<String>> goodsTop = template.boundZSetOps("shop:top" + shopId).rangeWithScores(0, -1);
            if (goodsTop.isEmpty()) {
                List<TravelGoods> goods = (List<TravelGoods>) result.getData();
                //将商品信息存入redis
                BoundZSetOperations<String, String> top = template.boundZSetOps("shop:top" + shopId);
                for (TravelGoods good : goods) {
                    top.add(JSONUtils.toJSONString(good), good.getSales());
                }
                shop.setTravelGoods(goods);

            } else {
                goodsList = new LinkedList();
                for (ZSetOperations.TypedTuple<String> top : goodsTop) {
                    String value = top.getValue();
                    System.out.println(value);
                    goodsList.add(JSONUtils.parse(value));
                }
            }

        }
        return new ResultVO(true, "查询成功", goodsList);
    }
}
